import { NextRequest, NextResponse } from "next/server"; import { getIronSession } from "iron-session"; import { SessionData, sessionOptions } from "@/lib/session"; import { prisma } from "@/lib/prisma"; import { notifyFileComment } from "@/lib/notifications"; export async function GET( request: NextRequest, { params }: { params: { id: string } } ) { const response = NextResponse.next(); const session = await getIronSession(request, response, sessionOptions); if (!session.isLoggedIn || !session.userId) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const comments = await prisma.comment.findMany({ where: { fileId: params.id }, include: { user: { select: { id: true, name: true, username: true, avatarPath: true }, }, }, orderBy: { createdAt: "asc" }, }); return NextResponse.json(comments); } export async function POST( request: NextRequest, { params }: { params: { id: string } } ) { const response = NextResponse.next(); const session = await getIronSession(request, response, sessionOptions); if (!session.isLoggedIn || !session.userId) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { content } = await request.json(); if (!content || !content.trim()) { return NextResponse.json({ error: "Le contenu est requis" }, { status: 400 }); } const file = await prisma.file.findUnique({ where: { id: params.id }, select: { id: true, name: true, userId: true }, }); if (!file) { return NextResponse.json({ error: "Fichier introuvable" }, { status: 404 }); } const comment = await prisma.comment.create({ data: { fileId: params.id, userId: session.userId, content: content.trim(), }, include: { user: { select: { id: true, name: true, username: true, avatarPath: true }, }, }, }); // Notify other commenters + file owner const commenter = await prisma.user.findUnique({ where: { id: session.userId }, select: { name: true, username: true }, }); const commenterName = commenter?.name || commenter?.username || "Quelqu'un"; // Get all unique users who commented on this file (excluding the current user) const otherCommenters = await prisma.comment.findMany({ where: { fileId: params.id, userId: { not: session.userId } }, select: { userId: true }, distinct: ["userId"], }); const usersToNotify = new Set(otherCommenters.map((c) => c.userId)); // Also notify file owner if they haven't commented if (file.userId && file.userId !== session.userId) { usersToNotify.add(file.userId); } for (const userId of Array.from(usersToNotify)) { await notifyFileComment(userId, commenterName, file.name, file.id); } return NextResponse.json(comment, { status: 201 }); }